package com.data.platform.core.utils;

import cn.hutool.core.net.NetUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Ip工具类
 */
public class IpUtils {
    private static final String[] IP_HEADERS = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR",
            "X-Real-IP"
    };

    public static String getClientIp() {
        return getClientIp(ServletUtils.getRequest());
    }

    /**
     * 获取客户端ip
     */
    private static String getClientIp(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            return "unknown";
        }

        for (String header: IP_HEADERS) {
            String ip = request.getHeader(header);
            if (StringUtils.isNotEmpty(ip) || !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        String ip = request.getRemoteAddr();

        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip);
    }

    /**
     * 获取id地址
     */
    public static String getLocalAddress(Integer port) {
        return NetUtil.getLocalhostStr() + ":" + port;
    }

    /**
     * 多级代理，取第一个ip为客户ip
     */
    private static String getMultistageReverseProxyIp(String ip) {
        if (Objects.nonNull(ip) && ip.contains(",")) {
            return ip.substring(ip.lastIndexOf(",") + 1).trim();
        }
        return "unknown";
    }
}
